package com.dragon.logical.service.auth.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dragon.logical.service.auth.IModRoleService;
import com.dragon.repository.entity.AdminRole;
import com.dragon.repository.entity.ModRole;
import com.dragon.repository.mapper.AdminRoleMapper;
import com.dragon.repository.mapper.ModRoleMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 模块角色表 服务实现类
 * </p>
 *
 * @author sy
 * @since 2023-07-20
 */
@Service
public class ModRoleServiceImpl extends ServiceImpl<ModRoleMapper, ModRole> implements IModRoleService {

    @Autowired
    ModRoleMapper mapper;
    @Autowired
    AdminRoleMapper adminRoleMapper;


    @Override
    public List<ModRole> listModRole(Integer adminId) {
        AdminRole adminRole = adminRoleMapper.selectOne(new QueryWrapper<AdminRole>().lambda().eq(AdminRole::getAdminId, adminId));
        if(adminRole == null){
            return null;
        }
        List<ModRole> modRoles = mapper.selectList(new QueryWrapper<ModRole>().lambda().eq(ModRole::getRoleId, adminRole.getRoleId()));
        return modRoles;
    }

    @Override
    public void addModRole(ModRole modRole) {
        mapper.insert(modRole);
    }

    @Override
    public void updateModRole(ModRole modRole) {
        mapper.updateById(modRole);
    }

    @Override
    public void deleteModRole(Integer id) {
        mapper.deleteById(id);
    }

    @Override
    public void chooseMod(Integer roleId, String modIds) {
        if(StrUtil.isNotBlank(modIds)){
            List<Integer> ids = Arrays.asList(modIds.split(",")).stream().map(s -> Integer.parseInt(s.trim())).collect(Collectors.toList());
            mapper.delete(new QueryWrapper<ModRole>().lambda().eq(ModRole::getRoleId, roleId));
            for (Integer id : ids) {
                ModRole modRole = new ModRole();
                modRole.setRoleId(roleId);
                modRole.setModId(id);
                mapper.insert(modRole);
            }
        }
    }

    @Override
    public List<ModRole> selectModListByRoleId(Integer roleId){
        List<ModRole> modRoles = mapper.selectList(new LambdaQueryWrapper<ModRole>().eq(ModRole::getRoleId,roleId));
        return modRoles;
    }
}
